﻿; (function ($) {

    $.fn.unionSelect2 = function (options) {
        var defaults = {
            selectedValues: [],
            urls: [],
            params: [],
            level: 1,
            isMultlple: false,
            selectedMax: 5,
            inputName: "",
            items: [],
            allowParent: false,
        }
        var $this = $(this);
        
        var id = $this.attr('id');
        var options = $.extend(defaults, options);
        var timeStamp = new Date().getMilliseconds() + "_" + id;

        var popId = "unionSelect_" + timeStamp;
        var baseBoxId = 'changeBoxs_' + timeStamp;
        var itemClass = 'item_' + timeStamp;
        var showItemClass = 'selectedItem_' + timeStamp;
        var removeShowItemClass = 'remove_' + timeStamp;
        var isSingle = options.level == 1;
        var selectedClass = isSingle ? 'select': 'changed';
        var selectedShowId = 'show_' + timeStamp;
        var confirmId = 'confirm_' + timeStamp;
        var inputId = 'input_' + timeStamp;


        function renderBaseElment(popId, baseBoxId, confirmId, inputId, cancelId, clearId) {
            var baseBoxClass = isSingle ? 'changeListBox' : 'chage_box2List';

            var basicHtml = '<div id="' + selectedShowId + '">' + '</div>'+
            '<select ' + (options.isMultlple ? 'multiple' : '') + ' name="' + options.inputName + '" id="' + inputId + '" style="display:none"></select>' +
                    '<i class="iconfont icon-down fr point orange trunDown"></i>' + 
                    '<div class="' +  baseBoxClass + '" id="' + popId + '" style="display:none">' +
                    '<div id="' + baseBoxId + '"></div>' +
                    '<div class="cl"></div>' + (isSingle ? '':
                    '<div class="tc sureBox mt15">' +
                        '<a id="' + confirmId + '" class="bgbule dibBtn withe point">确定</a>' +
                    '</div>' )
            '</div>';
            return basicHtml;
        }

        var basicHtml = renderBaseElment(popId, baseBoxId, confirmId, inputId);
        $(basicHtml).appendTo($this); //插入基本文档结构
        $this.addClass("chage_box");

        var $showSelected = $('#' + selectedShowId);
        var $boxs = $('#' + baseBoxId);
        var $pop = $('#' + popId);
        var isOn = false;
        $this.mouseover(function () {
            isOn = true;
        }).mouseout(function () {
            isOn = false;
        });
        
        var $input = $('#' + inputId);

        function getLevelId(level) {
            return 'Level_' + level + '_items_' + timeStamp;
        }

        function getLevelSelector(level) {
            return $('#' + getLevelId(level));
        }

        function renderBoxElement(level) {
            var divClass = isSingle ? ''
                                    : (level % 2 == 0 ? "chage_box2ListL c_666" : "chage_box2ListR");
            return '<div class="' + divClass + '" id="' + getLevelId(level) + '"></div>';
        }

        function getRootConfig(level, urls, paramNames) {
            var root, parent, child, option;
            
            paramNames = paramNames ? paramNames : 'parentId'; // 如果没有参数 就使用默认参数
            var paramName = typeof (paramNames) == 'string' ? paramNames : null;
            var url = typeof (urls) == 'string' ? urls : null;

            for (var i = 0; i < level; i++) {
                $(renderBoxElement(i)).hide().appendTo($boxs);
                child = {
                    url: url ? url : urls[i],
                    urlParamName: paramName ? paramName : paramNames[i],
                    level: i,
                };
                if (i == 0) {
                    root = child;
                } else {
                    parent.child = child;
                }
                parent = child;
            }

            return root;
        }

        function isSelected(value) {
            for (var i = 0, len = options.selectedValues.length; i < len; i++) {
                if (value === options.selectedValues[i].Value) {
                    return true;
                }
            }
            return false;
        }

        function renderItem(option, level) {
            return '<span data-value="' + option.Value + '" title="' + option.Text + '"  class="' + itemClass + (isSelected(option.Value) ? ' ' + selectedClass : '') + '">' + option.Text + '</span>';
        }

        //输出列表,返回的json是[{Text:"xxx",Value:"xxx"},...]
        function renderItems(items) {
            var html = '';
            for (var i = 0, len = items.length; i < len; i++) {
                html += renderItem(items[i])
            }
            return html;
        }

        function renderSelected(text, value) {
            return '<span class="changedBtn ' + showItemClass + '"><em>' + text + '</em><i class="iconfont fs14 icon-addcollapse ' + removeShowItemClass + '" data-value="' + value + '"></i></span>';
        }

        function setSelectedInputValues() {
            var values = [];
            var html = '';
            for (var i = 0, len = options.selectedValues.length; i < len; i++) {
                //values.push(options.selectedValues[i].Value);
                html += '<option value="' + options.selectedValues[i].Value + '" selected></option>';
            }
            $input.html(html)
        }

        function addItem(text, value) {
            if (!options.isMultlple) {
                options.selectedValues = [];
                $showSelected.html('');
            }
            options.selectedValues.push({
                Text: text,
                Value: value
            });
            var html = renderSelected(text, value);
            $(html).appendTo($showSelected);
            setTop();
            setSelectedInputValues();
        }

        function removeSelectedValue(value) {
            // 删除input值
            for (var i = 0, len = options.selectedValues.length; i < len; i++) {
                item = options.selectedValues[i];
                if (item.Value == value) {
                    options.selectedValues.splice(i, 1);
                    return;
                }
            }
        }

        function removeShowItem(value) {
            // 删除元素
            $('.' + removeShowItemClass).each(function () {
                var $this = $(this);
                if ($this.data('value') == value) {
                    $this.closest('.' + showItemClass).remove();
                }
            });
            setTop();
            setSelectedInputValues();
        }

        function switchItem(selector) {
            var value = selector.data('value');
            var text = selector.attr('title');
            var isRemove = !selector.is('.' + selectedClass);
            if (isSelected(value)) {
                if (isRemove) {
                    removeSelectedValue(value);
                    removeShowItem(value);
                }
            } else {
                addItem(text, value);
            }
        }

        function setClickFunction(selector, elementOptions) {
            selector.on("click", "." + itemClass, function () {
                var selected = $(this).is('.' + selectedClass);

                if (elementOptions.child) {
                    if (selected) {
                        return;
                    }
                    elementOptions.child.urlParamValue = $(this).data('value');
                    elementOptions.child.parentText = $(this).text();
                    loadItems(elementOptions.child);
                    getLevelSelector(elementOptions.level).children('.' + itemClass).removeClass(selectedClass);
                    $(this).addClass(selectedClass);
                } else {
                    if (!options.isMultlple) { // 单选
                        getLevelSelector(elementOptions.level).children('.' + itemClass).removeClass(selectedClass);
                    }
                    else if (!selected && options.selectedValues.length + 1 > options.selectedMax) {
                        //alert("最多只能选" + options.selectedMax + "个");
                        return;
                    }
                    if (options.allowParent) {
                        var levelItems = getLevelSelector(elementOptions.level);
                        var parentItem = levelItems.find('.' + itemClass).first();
                        if ($(this).data('value') != parentItem.data('value')) {
                            if (parentItem.is('.' + selectedClass)){
                                return;
                            }
                        }
                        else if (!parentItem.is('.' + selectedClass)) {
                            levelItems.children('.' + itemClass).each(function () {
                                var item = $(this);
                                if (item.is('.' + selectedClass)) {
                                    item.removeClass(selectedClass);
                                    switchItem(item);
                                }
                            });
                        }
                    }
                    switchItem($(this).toggleClass(selectedClass));
                }
            });
        }

        function getItems(parentValue) {
            var item, items = [];
            for (var i = 0, len = options.items.length; i < len; i++) {
                item = options.items[i];
                if((!item.ParentValue && !parentValue) || (item.ParentValue === parentValue)) {
                    items.push(item);
                }
            }
            return items;
        }

        function appendItems(items, parentValue) {
            var item;
            for (var i = 0, len = items.length; i < len; i++) {
                item = items[i];
                if (!item.ParentValue) {
                    item.ParentValue = parentValue;
                }
                options.items.push(item);
            }
        }

        function loadItems(elementOptions) {
            var params = {}, items = [];
            var parentValue = !!elementOptions.urlParamValue
                                                    ? elementOptions.urlParamValue
                                                    : "";
            var parentText = !!elementOptions.urlParamValue
                                                    ? elementOptions.parentText
                                                    : "";
            if (elementOptions.urlParamName) {
                params[elementOptions.urlParamName] = parentValue;
            }
            var $currentElement = getLevelSelector(elementOptions.level);
            $currentElement.html("加载中...");//clear old item

            var handlerItems = function (items) {
                if (!items || !items.length) {
                    items = [];
                }
                $currentElement.html(options.allowParent && elementOptions.level > 0
                    ? renderItem({
                        Text: parentText,
                        Value: parentValue,
                    })
                    : '');
                $(renderItems(items)).appendTo($currentElement);
                $currentElement.show();
            }

            var ajaxHandlerItems = function (items) {
                handlerItems(items);
                appendItems(items, parentValue); // 加载数据本地缓存
            }

            items = getItems(parentValue); // 读取缓存
            if (items.length) {
                handlerItems(items);
            } else {
                $.post(elementOptions.url, params, ajaxHandlerItems);
            }

        }

        function initSelectedItems() {
            for (var i = 0, len = options.selectedValues.length; i < len; i++) {
                var option = options.selectedValues[i];
                var html = renderSelected(option.Text, option.Value);
                $(html).appendTo($showSelected);
            }
            setSelectedInputValues();
        }

        // 点击 x 删除
        $showSelected.on('click', '.' + removeShowItemClass, function () {
            var value = $(this).data('value');
            $('.' + itemClass).each(function () { // 取消插件内的选定
                var $this = $(this);
                if ($this.data('value') == value) {
                    $this.removeClass(selectedClass);
                }
            });
            $(this).closest('.' + showItemClass).remove(); // 删除选定的
            removeSelectedValue(value); // 删除值
            setSelectedInputValues();
            setTop();
        });


        initSelectedItems();

        function init() {
            var rootElementConfig = getRootConfig(options.level, options.urls, options.paramNames);
            loadItems(rootElementConfig);
            var temp = rootElementConfig;
            while (temp) {
                setClickFunction(getLevelSelector(temp.level), temp);
                temp = temp.child;
            }
        }
        init();

        function setTop() {
            var height = $this.height();
            $pop.css('top', height + 10);
        }

        function toggle($selector) {
            isup = $selector.is('.trunUp');
            if (isup) {
                $pop.fadeOut(400);
                $selector.removeClass('trunUp');
            } else {
                setTop();
                $pop.fadeIn(400);
                $selector.addClass('trunUp');
            }
        }

        $this.on('click', '.icon-down', function (event) {
            var _this = $(this)
            toggle(_this);

        });

        $('#' + confirmId).click(function () {
            toggle($this.find('.icon-down'));
        });

        $(document).on("mousedown", function (e) {
            if (!isOn) {
                if ($pop.is(":visible")) {
                    toggle($this.find('.icon-down'));
                }
            }
        });

        $this.on("mousedown", function (e) {
            var target = $(e.target)
            if (target.closest('#' + selectedShowId + ',i,#' + popId).length == 0) {
                toggle($this.find('.icon-down'));
            }
        });
    }
})(jQuery);